import React, { useState, useEffect } from "react";
import {
  ConfigProvider,
  Button,
  Col,
  Form,
  Row,
  Space,
  Pagination,
} from "antd";
import DebounceSelect from "./DebounceSelect";
import { pinyin } from "pinyin-pro";
import ShowDetails from "./ShowDetails";

import "./main.css";

export default function Main(props) {
  const onFinish = (values) => {
    const { getList } = window?.electron || {};
    const { term_name, term_ename, standard_name, standard_no } = values;
    const serchObj = {
      term_name,
      term_ename,
      standard_name,
      standard_no,
      pageSize: 1000,
    };
    for (let i in serchObj) {
      if (!serchObj[i]) {
        serchObj[i] = null;
      }
    }
    getList(serchObj).then((result) => {
      setTableList(result);
      setTotle(result.length);
    });
  };
  const [form] = Form.useForm();

  const [allOptionData, setAllOptionData] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [value, setValue] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [totle, setTotle] = useState(0);
  const [detailsOpenObj, SetDetailsOpenObj] = useState({});
  const [currenpageSize, setcurrenpageSize] = useState(10);
  const [valueObj, setValueObj] = useState({});
  const formStyle = {
    maxWidth: "none",
    padding: 24,
  };

  useEffect(() => {
    findAllData();
  }, [detailsOpenObj]);

  const fetchUser = (value, type) => {
    const { serchOptionList } = window.electron || {};
    let serchType = type;

    // 查询字段对比
    let serachSring = "";
    serachSring = value;
    if (type === "term_name" || type === "standard_name") {
      if (/^[\u4e00-\u9fff]+$/.test(value)) {
        // 变成拼音去查
        serachSring = pinyin(value, { toneType: "none" }).replace(/\s+/g, "");
        serchType = type + "_pinyin";
      } else {
        serachSring = value;
        serchType = type + "_pinyin";
      }
    }

    return serchOptionList({ keys: serchType, values: serachSring }).then(
      (result) => {
        const newResult = result.reduce((acc, cur) => {
          let obj = {
            value: cur[type],
            label: cur[type],
          };
          acc.push(obj);
          return acc;
        }, []);
        return newResult;
      }
    );

    // this.setState({ allOptionData, fetching: false });
  };

  const findAllData = (type) => {
    const { getList, listAllSum } = window.electron || {};
    listAllSum().then((rows) => {
      setTotle(rows[0].total);
    });
    const values = type === "reset" ? {} : valueObj;
    getList({ ...values, page: currentPage, pageSize: currenpageSize }).then(
      (result) => {
        console.log(result);
        setTableList(result);
      }
    );
  };

  // 页码变化
  const pageChange = (page, pageSize) => {
    setcurrenpageSize(pageSize);
    setCurrentPage(page);
  };

  useEffect(() => {
    findAllData();
  }, [currentPage, currenpageSize]);

  const setValueObjFunc = (keys, value) => {
    let newValueObj = valueObj;
    newValueObj[keys] = value;
    setValueObj(newValueObj);
  };
  return (
    <ConfigProvider>
      {/* 直接进入查询页面 */}
      <div className="bigPageBox">
        <div className="scerachBox">
          <Form
            form={form}
            name="advanced_search"
            style={formStyle}
            onFinish={onFinish}
          >
            <Row gutter={24}>
              <Col span={8}>
                <Form.Item name="term_name" label="话术中文名称">
                  <DebounceSelect
                    placeholder="输入关键字查询"
                    fetchOptions={(value) => fetchUser(value, "term_name")}
                    onChange={(value) => {
                      console.log(value);
                      setValueObjFunc("term_name", value);
                    }}
                    style={{
                      width: "100%",
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="term_ename" label="术语英文名称">
                  <DebounceSelect
                    value={valueObj["term_ename"]}
                    onChange={(value) => {
                      setValueObjFunc("term_ename", value);
                    }}
                    placeholder="输入关键字查询"
                    fetchOptions={(value) => fetchUser(value, "term_ename")}
                    style={{
                      width: "100%",
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="standard_name" label="标准名称">
                  <DebounceSelect
                    value={valueObj["standard_name"]}
                    onChange={(value) => {
                      setValueObjFunc("standard_name", value);
                    }}
                    placeholder="输入关键字查询"
                    fetchOptions={(value) => fetchUser(value, "standard_name")}
                    style={{
                      width: "100%",
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={8}>
                <Form.Item name="standard_no" label="标准编号">
                  <DebounceSelect
                    value={valueObj["standard_no"]}
                    onChange={(value) => {
                      setValueObjFunc("standard_no", value);
                    }}
                    placeholder="输入关键字查询"
                    fetchOptions={(value) => fetchUser(value, "standard_no")}
                    style={{
                      width: "100%",
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
            <div
              style={{
                textAlign: "right",
              }}
            >
              <Space size="small">
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  onClick={() => {
                    form.resetFields();
                    setValueObj({});
                    findAllData("reset");
                  }}
                >
                  清除搜索条件
                </Button>
              </Space>
            </div>
          </Form>
        </div>
        <div className="search-result-list">
          {tableList?.map((item) => {
            const { standard_name, standard_no, term_name, term_ename, id } =
              item;
            return (
              <div key={id} className="listItem">
                <p style={{ fontWeight: "bold" }}>
                  标准名称：<span>{standard_name}</span>----
                  <span>{standard_no}</span>
                </p>

                <p className="termNameBox" style={{}}>
                  {term_name}
                  <div className="bthBox">
                    <span
                      onClick={() => {
                        let detailsOpenObj = {
                          open: true,
                          title: "查看详情",
                          type: "view",
                          details: item,
                        };
                        SetDetailsOpenObj(detailsOpenObj);
                      }}
                    >
                      查看详情
                    </span>
                    <span
                      onClick={() => {
                        let detailsOpenObj = {
                          open: true,
                          title: "修改意见",
                          type: "inset",
                          details: item,
                        };
                        SetDetailsOpenObj(detailsOpenObj);
                      }}
                    >
                      修改意见
                    </span>
                  </div>
                </p>
                <p>{term_ename}</p>
              </div>
            );
          })}
          <Pagination
            current={currentPage}
            onChange={pageChange}
            defaultCurrent={1}
            total={totle}
          />
        </div>
      </div>
      {detailsOpenObj?.open && (
        <ShowDetails
          {...detailsOpenObj}
          SetDetailsOpenObj={(obj) => SetDetailsOpenObj(obj)}
        />
      )}
    </ConfigProvider>
  );
}
